import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/detail_item.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

import '../../../components/app_conifg.dart';

///购物袋页控制器
class BagsController extends BaseController with SingleGetTickerProviderMixin {
  ///列表刷新控制器
  RefreshController listCtr = RefreshController();
  var detailOverlay = null;
  late AnimationController animationController;
  late Animation<double> animation;
  late Animation<double> changeSize;

  ///购物车信息
  Map<String, dynamic> carInfo = {};

  // 用于购物车（）的显示
  int showGoodNum = 0;

  ///是否全选商品
  bool isSelectAll = true;

  ///商品分组列表
  List goodsGroupList = [];

  ///是否批量管理
  bool isBatchMgr = false;

  ///商品总数量
  int totalNum = 0;

  ///商品总价格
  String totalPrice = '0';

  String pricePay = '0';

  @override
  void onInit() async {
    super.onInit();
    animationController = AnimationController(
      duration: const Duration(milliseconds: 250),
      reverseDuration: const Duration(milliseconds: 200),
      vsync: this,
    );
    animation = Tween(begin: 0.0, end: 1.0).chain(CurveTween(curve: Curves.ease)).animate(animationController)
      ..addListener(() {
        update();
      });
    changeSize = Tween(begin: 0.0, end: 300.h).animate(animationController);

    animationController.addStatusListener((AnimationStatus status) {
      //执行完成后反向执行
      if (status == AnimationStatus.completed) {
        // _controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        detailOverlay.remove();
        detailOverlay.dispose();
        detailOverlay = null;
      }
    });
    await getCarList();
    update();
    //监听刷新购物车
    EventMgr.on(EventType.refreshCar, (arg) async {
      logger.d('刷新');
      await getCarList();
      update();
    });

    EventMgr.on(EventType.refreshLogin, (arg) async {
      logger.d('刷新');
      await getCarList();
      update();
    });

    UmengCommonSdk.onPageStart('购物车');
  }

  ///获取购物车列表
  Future getCarList() async {
    Tools.showLoading();
    return Network.getCarList().then((value) {
      Tools.hideLoading();
      carInfo = value;
      goodsGroupList = value['goodsGroup'];
      isSelectAll = isSelectAllGoods();
      totalNum = getTotalNum();
      totalPrice = value['priceTotal'].toString();
      pricePay = value['pricePay'].toString();

      calculateShowGoodNum();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///全选、反选
  void toggleAllSelect(bool value) {
    isSelectAll = value;
    setAllGoodsToggleSelect(value);
    Network.chooseMulti(getIdsBySelectAll(value), value ? 1 : 0).then((value) async {
      await getCarList();
      update();
    });
  }

  ///获取选中或取消选中的id列表
  List<String> getIdsBySelectAll(bool isSelect) {
    List<String> arr = [];
    int selected = isSelect ? 1 : 0;
    for (int i = 0; i < goodsGroupList.length; i++) {
      var item = goodsGroupList[i];
      if (item['goodsList'] != null) {
        for (int j = 0; j < item['goodsList'].length; j++) {
          if (item['goodsList'][j]['isSelect'] == selected) {
            arr.add(item['goodsList'][j]['cartId']);
          }
        }
      }
    }
    return arr;
  }

  ///设置所有商品全选和反选
  void setAllGoodsToggleSelect(bool isSelect) {
    for (int i = 0; i < goodsGroupList.length; i++) {
      var item = goodsGroupList[i];
      if (item['goodsList'] != null) {
        for (int j = 0; j < item['goodsList'].length; j++) {
          item['goodsList'][j]['isSelect'] = isSelect ? 1 : 0;
        }
      }
    }
  }

  ///获取是否选中所有商品
  bool isSelectAllGoods() {
    for (int i = 0; i < goodsGroupList.length; i++) {
      var item = goodsGroupList[i];
      if (item['goodsList'] != null) {
        for (int j = 0; j < item['goodsList'].length; j++) {
          if (item['goodsList'][j]['isSelect'] == 0) {
            return false;
          }
        }
      }
    }
    return true;
  }

  ///选中和取消选中单个商品
  void toggleSelectSingleGoods(int groupIndex, int index, bool isSelect) {
    goodsGroupList[groupIndex]['goodsList'][index]['isSelect'] = isSelect ? 1 : 0;
    if (!isSelect) {
      isSelectAll = false;
    } else {
      isSelectAll = isSelectAllGoods();
    }
    update();
  }

  ///获取已选商品总数量
  int getTotalNum() {
    int total = 0;
    for (var item in goodsGroupList) {
      for (var child in item['goodsList']) {
        if (child['isSelect'] == 1) {
          total += 1;
        }
      }
    }
    return total;
  }

  void calculateShowGoodNum() {
    int num = 0;
    for (var item in goodsGroupList) {
      if (item['goodsList'] != null) {
        // 检查 goodsList 是否为 null
        for (var child in item['goodsList']) {
          int buyNum = child['buyNum']; // 直接获取整数
          int specNum = child['specNum']; // 直接获取整数
          num += (buyNum * specNum);
        }
      }
    }
    showGoodNum = num;
  }

  ///管理购物车
  void clickManager() {
    isBatchMgr = !isBatchMgr;
    update();
  }

  ///商品结算
  void goodsSettlement() {
    if (getSelectedIds('cartId').length == 0) {
      Tools.showToast('未选择商品');
      return;
    }
    jumpFillOrder();
  }

  ///跳转填写订单页
  void jumpFillOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 0;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['sid'] = AppData.sid;
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///已选商品列表
  List<Map<String, dynamic>> getPlaceOrderGoodsList() {
    List<Map<String, dynamic>> arr = [];
    for (var item in goodsGroupList) {
      for (var child in item['goodsList']) {
        if (child['isSelect'] == 1) {
          Map<String, dynamic> info = {};
          info['buyNum'] = child['buyNum'];
          info['goodsId'] = child['goodsId'];
          info['isSelect'] = 1;
          info['isSend'] = 0;
          info['specNum'] = child['specNum'];
          arr.add(info);
        }
      }
    }
    return arr;
  }

  ///删除购物车商品
  void deleteCarGoods(String id, int groupIndex, int index) {
    Network.deleteCarGoods(id).then((value) {
      if (value) {
        Tools.showToast('删除成功');
        goodsGroupList = [];
        update();
        // Future.delayed(const Duration(milliseconds: 1));
        EventMgr.send(EventType.refreshCar);
      } else {
        Tools.showToast('删除失败');
      }
    });
  }

  ///收藏商品
  void collectGoods(String id) {
    Network.collect(id).then((value) {
      if (value) {
        Tools.showToast('收藏成功');
      } else {
        Tools.showToast('收藏失败');
      }
    });
  }

  ///获取选中的商品id列表
  List<String> getSelectedIds(String key) {
    List<String> arr = [];
    for (var item in goodsGroupList) {
      for (var child in item['goodsList']) {
        if (child['isSelect'] == 1) {
          arr.add(child[key]);
        }
      }
    }
    return arr;
  }

  ///批量删除商品
  void multiDeleteGoods() {
    if (getSelectedIds('cartId').length == 0) {
      Tools.showToast('未选择商品');
      return;
    }
    Network.batchDeleteCarGoods(getSelectedIds('cartId')).then((value) {
      if (value) {
        Tools.showToast('删除成功');
        goodsGroupList = [];
        EventMgr.send(EventType.refreshCar);
      } else {
        Tools.showToast('删除失败');
      }
    });
  }

  ///批量收藏商品
  void multiCollectGoods() {
    if (getSelectedIds('cartId').length == 0) {
      Tools.showToast('未选择商品');
      return;
    }
    Network.collectMut(getSelectedIds('goodsId')).then((value) {
      if (value) {
        Tools.showToast('收藏成功');
      } else {
        Tools.showToast('收藏失败');
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    animationController.dispose();
    EventMgr.off(EventType.refreshCar);
    EventMgr.off(EventType.refreshLogin);
    UmengCommonSdk.onPageEnd('购物车');
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    print("刷新购物车");

    if (AppData.isLogin) {
      await getCarList();
    } else {
      carInfo = {};
      showGoodNum = 0;
      isSelectAll = true;
      goodsGroupList = [];
      isBatchMgr = false;
      totalNum = 0;
      totalPrice = '0';
      pricePay = '0';
    }

    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
  }

  ///监听列表下拉刷新
  void onListRefresh() async {
    await getCarList();
    listCtr.refreshCompleted(resetFooterState: true);
  }

  ///监听列表上拉加载
  void onListLoading() async {}

  ///显示优惠明细
  void toggleDetail(BuildContext context) {
    if (detailOverlay == null) {
      createDetailPopup(context);
    } else {
      removeDetailPopup();
    }
  }

  ///创建优惠明细弹框
  void createDetailPopup(BuildContext context) {
    detailOverlay = OverlayEntry(
      builder: (context) {
        return AnimatedBuilder(
          animation: animationController,
          builder: (context, child) {
            return Opacity(
              opacity: animation.value,
              child: BaseInteractive(
                childWidget: Container(
                  color: Colors.black.withOpacity(0.5),
                  margin: EdgeInsets.only(
                    bottom: MediaQuery.of(context).padding.bottom + 48.h,
                  ),
                  child: Stack(
                    children: [
                      Positioned(
                        bottom: 0,
                        left: 0,
                        child: BaseInteractive(
                          childWidget: Container(
                            width: 375.w,
                            height: changeSize.value,
                            decoration: const BoxDecoration(
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(25),
                                topRight: Radius.circular(25),
                              ),
                              color: Colors.white,
                            ),
                            child: Stack(
                              children: [
                                Container(
                                  width: 375.w,
                                  height: 55.h,
                                  decoration: const BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(25),
                                      topRight: Radius.circular(25),
                                    ),
                                    color: Color(0xffffffff),
                                  ),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        '优惠明细',
                                        style: setTextStyle(15, FontWeight.w700, Colors.black),
                                      ),
                                    ],
                                  ),
                                ),
                                Positioned(
                                  right: 18,
                                  top: 18,
                                  child: BaseInteractive(
                                    childWidget: const Icon(
                                      Icons.close,
                                      color: Colors.black,
                                    ),
                                    onClick: () {
                                      removeDetailPopup();
                                    },
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 55.h),
                                  decoration: const BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.all(Radius.circular(0)),
                                  ),
                                  child: SingleChildScrollView(
                                    // Wrap with SingleChildScrollView
                                    child: Column(
                                      children: [
                                        DetailItem(
                                          label: '商品总额',
                                          content: carInfo['priceTotal'].toString(),
                                          labelStyle: LabelStyle.title,
                                          contentStyle: ContentStyle.title,
                                        ),
                                        DetailItem(
                                          label: '立减',
                                          content: carInfo['priceDiscount'].toString(),
                                          contentStyle: ContentStyle.discount,
                                        ),
                                        DetailItem(
                                          label: '共减',
                                          labelStyle: LabelStyle.title,
                                          content: carInfo['priceDiscount'].toString(),
                                          contentStyle: ContentStyle.discountTotal,
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          onClick: () {},
                        ),
                      ),
                    ],
                  ),
                ),
                onClick: () {
                  removeDetailPopup();
                },
              ),
            );
          },
        );
      },
    );
    Overlay.of(context).insert(detailOverlay);
    animationController.forward();
  }

  ///移除优惠明细弹框
  void removeDetailPopup() {
    animationController.reverse();
  }
}
